<?php
namespace Common\Model;
use Common\Model\AiModel;
class WxServerModel extends AiModel {
    protected $tableName = 'wx_news'; 
	public function p_all($txt,$openid='') {
		$ary = D('WxNews')->where("match_type>0 AND keywords='{$txt}'")->order('id DESC')->select();
		$i=0;
		foreach ($ary as $item) {
			if (++$i<=10) { #最多5个图文
                if($item['id']==10){
                    #$item['description'] = $openid;
                    #获取用户积分
                    $score = D('UserWechat')->getUserScore($openid);
                    $content = '您当前可用积分：'.$score.'分
点击这里，立即使用积分。
温馨提示：此积分可在啾啾商城中抵现金使用，使用规则为100积分=1元。';
                    $item['description'] = $content;
                }
				$data[$item['id']] = $item;

			}
		}

		return $data;
	}

	public function getUserScore($openid){
        $score = D('UserWechat')->getUserScore($openid);
        return $score;
    }

    public function getUserNickname($openid=''){
	   return M('UserWechat')->where("openid='{$openid}'")->getField('nickname');
    }
	
	public function p_part($keys) {
		if (!is_array($keys)) $keys = array($keys);
		$data = array();
		$i=0;
		foreach ($keys as $k) {
			$ary = D('WxNews')->where("match_type=2 AND keywords LIKE '%{$k}%' ")->order('id DESC')->select();
			foreach ($ary as $item) {
				if (++$i<=10) { #最多5个图文
					$data[$item['id']] = $item;
				}
			}
		}
		return $data;
	}
	
	public function _format($ary) {
		if ( $ary['msg_type']=='2') { #文本
			return $ary['content'];
		} elseif ( $ary['msg_type']=='1' ) { #图文
			$data = array(
							'Title'			=>$ary['title'],
							'Description'	=>$ary['description'],
							'PicUrl'		=> $ary['img_url'],
							'Url'			=> DOMAIN.U('WxNews/view?id='.$ary['id']."&openid=".$GLOBALS['from_openid']."&token=".md5($GLOBALS['from_openid'].USER_KEY)),
						 );
			return $data;
		} else {
			return false;
		}
	}

	public function login(){
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APP_ID."&redirect_uri=".URL."&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
		@header("location:".$url);
		exit(0);
	}
	
}